package net.wicp.tams.commons.binlog.event;

import org.apache.commons.lang.ArrayUtils;

import net.wicp.tams.commons.Result;
import net.wicp.tams.commons.apiext.ByteUtil;
import net.wicp.tams.commons.binlog.bean.EventBean;
import net.wicp.tams.commons.binlog.bean.TableMapBean;
import net.wicp.tams.commons.binlog.constant.ColumnType;
import net.wicp.tams.commons.io.UnsignedLong;

public class TableMapEvent extends AbsEvent {
	private long tableId;
	private int flags;
	private String schemaName;
	private String tableName;
	private UnsignedLong columnCount;
	private ColumnType[] columnTypes;
	private int[] metaDefs;
	private byte[] nullBits;

	// columns present bitmap的bits set个数来

	public TableMapEvent(EventBean event) {
		super(event);
	}

	@Override
	public Result parseBody() {
		int postHeadLength = event.getHead().getEventType().getPostHeaderLength();
		if (postHeadLength == -1) {
			return Result.getError("没有初始化，FormatDescription事件必须第一个读.");
		}
		if (postHeadLength == 6) {
			tableId = ByteUtil.readLongL(readSubByte(4));
		} else {
			tableId = ByteUtil.readLongL(readSubByte(6));
		}
		flags = ByteUtil.readIntL(readSubByte(2));
		int schemaNameLength = ByteUtil.readIntL(readSubByte(1));
		schemaName = ByteUtil.readString(readSubByte(schemaNameLength));
		skip(1);
		int tableNameLength = ByteUtil.readIntL(readSubByte(1));
		tableName = ByteUtil.readString(readSubByte(tableNameLength));
		skip(1);
		columnCount = readUnsignedLong();
		columnTypes = new ColumnType[columnCount.intValue()];
		for (int i = 0; i < columnCount.intValue(); i++) {
			columnTypes[i] = ColumnType.get(readByte());
		}

		UnsignedLong meteCount = readUnsignedLong();
		byte[] meteBytes = readSubByte(meteCount.intValue());
		metaDefs = new int[columnCount.intValue()];
		int metapos = 0;
		for (int i = 0; i < columnCount.intValue(); i++) {
			int length = columnTypes[i].getMetaLen();
			switch (columnTypes[i]) {
			case SET:
			case ENUM:
			case STRING:
				metaDefs[i] = ByteUtil.readIntB(ArrayUtils.subarray(meteBytes, metapos, metapos + length));
				break;
			default:
				metaDefs[i] = ByteUtil.readIntL(ArrayUtils.subarray(meteBytes, metapos, metapos + length));
				break;
			}
			metapos = metapos + length;
		}

		int null_bitmapLength = (columnCount.intValue() + 7) / 8;
		nullBits = readSubByte(null_bitmapLength);
		TableMapBean.tbs.put(tableId,
				TableMapBean.builder().tableId(tableId).flags(flags).schemaName(schemaName).tableName(tableName)
						.columnCount(columnCount.intValue()).columnTypes(columnTypes).metaDefs(metaDefs)
						.nullBits(nullBits).build());
		return Result.getSuc();
	}

}
